package com.dferreira.axil.controller.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.component.UISelectItems;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import com.dferreira.axil.model.Categoria;

@FacesConverter(forClass = Categoria.class)
public class CategoriaConverter implements Converter {

	@SuppressWarnings("unchecked")
	@Override
	public Categoria getAsObject(FacesContext arg0, UIComponent componente, String valor) {
		HtmlSelectOneMenu menu = (HtmlSelectOneMenu) componente;
		UISelectItems itens = (UISelectItems) menu.getChildren().get(1);
		List<Categoria> categorias = (List<Categoria>) itens.getValue();
		
		for (Categoria categoria : categorias) {
			if(categoria.getId().equals(new Long(valor)))
				return categoria;
		}
		
		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		return ((Categoria)arg2).getId().toString();
	}

}
